package com.dream.web.interceptor;


import com.dream.common.constans.RedisKeysDefine;
import com.dream.common.exception.RespErrorException;
import com.dream.common.utils.DateUtils;
import com.dream.common.utils.ThreadContextUtil;
import com.dream.entity.UserAccountRegisterResponseBean;
import com.dream.service.ProcedureServiceImpl;
import com.dream.service.basic.RedisCacheService;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 登录 签名
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Resource
    private RedisCacheService redisCacheService;
    @Resource
    private ProcedureServiceImpl procedureService;

    private static List<String> ip_white_list = new ArrayList<>();

    static {
    }


    /**
     * 判断是否白名単ip
     */
    public static boolean isWhitelist(String ip) {
        return !StringUtils.isEmpty(ip) && ip_white_list.contains(ip);
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String user = request.getHeader("user");
        String pwd = request.getHeader("pwd");
        ThreadContextUtil.put("user", user);
        if (StringUtils.isEmpty(user)) {
            throw new RespErrorException("请登录后重试！" + request.getRequestURI());
        }
        if (StringUtils.isEmpty(pwd)) {
            throw new RespErrorException("密码不正确！" + request.getRequestURI());
        }
        UserAccountRegisterResponseBean userInfo = redisCacheService.getObject(RedisKeysDefine.LOGIN_ACCOUNT.concat(user), UserAccountRegisterResponseBean.class);
        if (userInfo == null) {
            throw new RespErrorException("未发现此用户，请登录后重试！" + request.getRequestURI());
        }
        if (StringUtils.isEmpty(pwd) || !pwd.equals(userInfo.pwd)) {
            throw new RespErrorException("密码不正确，请重新登陆！" + request.getRequestURI());
        }
        if (DateUtils.getTimeMillis(userInfo.time) < System.currentTimeMillis()) {
            throw new RespErrorException("账号已到期！" + request.getRequestURI());
        }
        return true;
//        return procedureService.tokenValidate(request,response);
    }


}

